package com.lbb.waimai.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtHelper {
    //注意jwt没操作30分钟后会自动下线
    //过期时间ms
    private static long tokenExpiration = 24*60*60*1000;
    //签名秘钥
    private static String tokenSignKey = "sfjhsds";

    //从请求头中获取用户id
    public static Long getUserId(HttpServletRequest request){
        String token = request.getHeader("token");
        return getUserId(token);
    }
    //根据用户参数生成token
    public static String createToken(Long userId) {
        String token = Jwts.builder()
                .setSubject("waimai") //分类
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))//设置过期时间
                .claim("userId", userId) //设置用户id
                .signWith(SignatureAlgorithm.HS512, tokenSignKey) //设置签名hash
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    //通过token，获得用户id
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }
    public static void main(String[] args) {
        String token = JwtHelper.createToken(11L);
//        String token = "eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSyk3LKlbSUUqtKFCyMjQzNbQwsDQ3MNZRKi1OLfJMUbIyNTGrBQBVerLDLAAAAA.-p5kPok2XSqIjqBExANCS3ZMPG9NOh30NfFfuGte1sFlxAVab1DCMtBtuZz2xGcU8JYz25_28lbYjpS3R8tKtw";


        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
    }
}

